/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.security.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.util.Assert;

/**
 * 抽象配置
 *
 * @param <C> 自身类型
 * @author zeng
 */
public abstract class AbstractSecurityConfigurer<C extends AbstractSecurityConfigurer<C>>
    extends AbstractHttpConfigurer<C, HttpSecurity> {
  protected AuthenticationSuccessHandler successHandler =
      new SavedRequestAwareAuthenticationSuccessHandler();
  protected AuthenticationFailureHandler failureHandler =
      new SimpleUrlAuthenticationFailureHandler();

  /**
   * 成功处理器
   *
   * @param authenticationSuccessHandler 处理方法
   * @return this
   */
  public C successHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
    this.successHandler = authenticationSuccessHandler;
    return getThis();
  }

  /**
   * 失败处理器
   *
   * @param failureHandler 处理方法
   * @return this
   */
  public C failureHandler(AuthenticationFailureHandler failureHandler) {
    Assert.notNull(failureHandler, "failureHandler cannot be null");
    this.failureHandler = failureHandler;
    return getThis();
  }

  @SuppressWarnings("all")
  protected C getThis() {
    return (C) this;
  }
}
